package com.globallogic.jira.gadget.utils;

import java.util.ArrayList;
import java.util.List;

import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.link.IssueLinkManager;
import com.atlassian.jira.issue.search.SearchException;
import com.atlassian.jira.issue.search.SearchResults;
import com.atlassian.jira.jql.builder.JqlQueryBuilder;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.web.bean.PagerFilter;
import com.atlassian.query.Query;

/**
 * @author anton.pereverziev
 * @author yegor.chumakov
 *         <p/>
 *         A utility class for convenient retrieving projects or issues.
 */
public class Search {

    @SuppressWarnings("deprecation")
    public static List<Issue> getIssuesFromProject(Long pid, String issueType,
	    String fixVersion, boolean includeOrphans) throws SearchException {

	JqlQueryBuilder builder = JqlQueryBuilder.newBuilder();

	if (fixVersion == null || fixVersion.equals("All")) {
	    builder.where().project(pid).and().issueType(issueType);
	} else {
	    builder.where().project(pid).and().issueType(issueType).and()
		    .fixVersion(fixVersion);
	}

	Query query = builder.buildQuery();
	SearchResults results = null;

	results = ComponentManager
		.getInstance()
		.getSearchService()
		.search(ComponentManager.getInstance()
			.getJiraAuthenticationContext().getUser(), query,
			PagerFilter.getUnlimitedFilter());

	List<Issue> issues = new ArrayList<Issue>();

	IssueLinkManager issueLinkManager = ComponentManager.getInstance()
		.getIssueLinkManager();

	for (Issue issue : results.getIssues()) {

	    if (issueLinkManager.getInwardLinks(issue.getId()).size() != 0
		    && issueLinkManager.getOutwardLinks(issue.getId()).size() == 0)
		issues.add(issue);

	    if (includeOrphans
		    && issueLinkManager.getInwardLinks(issue.getId()).size() == 0
		    && issueLinkManager.getOutwardLinks(issue.getId()).size() == 0)
		issues.add(issue);
	}
	return issues;
    }

    public static Project getProject(Long pid) throws SearchException {
	return ComponentManager.getInstance().getProjectManager()
		.getProjectObj(pid);

    }
}
